package com.farm.project.controller;

import com.farm.project.domain.Tasklink;
import com.farm.project.domain.Tasknode;
import com.farm.project.service.TasklinkServiceInter;
import com.farm.project.service.TasknodeServiceInter;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.annotation.Resource;
import com.farm.web.easyui.EasyUiUtils;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import javax.servlet.http.HttpSession;
import com.farm.core.page.RequestMode;
import com.farm.core.page.OperateType;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.result.DataResult;
import com.farm.core.page.ViewMode;
import com.farm.web.WebUtils;

/* *
 *功能：任务关系控制层
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@RequestMapping("/tasklink")
@Controller
public class TasklinkController extends WebUtils {
	private final static Logger log = Logger.getLogger(TasklinkController.class);
	@Resource
	private TasklinkServiceInter taskLinkServiceImpl;
	@Resource
	private TasknodeServiceInter taskNodeServiceImpl;

	/**
	 * 查询结果集合
	 * 
	 * @return
	 */
	@RequestMapping("/query")
	@ResponseBody
	public Map<String, Object> queryall(DataQuery query, HttpServletRequest request) {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			query = EasyUiUtils.formatGridQuery(request, query);
			DataResult result = taskLinkServiceImpl.createTasklinkSimpleQuery(query).search();
			return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 提交修改数据
	 * 
	 * @return
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public Map<String, Object> editSubmit(Tasklink entity, HttpSession session) {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			entity = taskLinkServiceImpl.editTasklinkEntity(entity, getCurrentUser(session));
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).putAttr("entity", entity).returnObjMode();

		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 提交新增数据
	 * 
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Map<String, Object> addSubmit(Tasklink entity, HttpSession session) {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			entity = taskLinkServiceImpl.insertTasklinkEntity(entity, getCurrentUser(session));
			return ViewMode.getInstance().setOperate(OperateType.ADD).putAttr("entity", entity).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 删除数据
	 * 
	 * @return
	 */
	@RequestMapping("/del")
	@ResponseBody
	public Map<String, Object> delSubmit(String ids, HttpSession session) {
		try {
			for (String id : parseIds(ids)) {
				taskLinkServiceImpl.deleteTasklinkEntity(id, getCurrentUser(session));
			}
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	@RequestMapping("/list")
	public ModelAndView index(HttpSession session) {
		return ViewMode.getInstance().returnModelAndView("project/TasklinkResult");
	}

	/**
	 * 显示详细信息（修改或浏览时）
	 *
	 * @return
	 */
	@RequestMapping("/form")
	public ModelAndView view(RequestMode pageset, String ids) {
		try {
			switch (pageset.getOperateType()) {
			case (0): {// 查看
				return ViewMode.getInstance().putAttr("pageset", pageset)
						.putAttr("entity", taskLinkServiceImpl.getTasklinkEntity(ids))
						.returnModelAndView("project/TasklinkForm");
			}
			case (1): {// 新增
				return ViewMode.getInstance().putAttr("pageset", pageset).returnModelAndView("project/TasklinkForm");
			}
			case (2): {// 修改
				return ViewMode.getInstance().putAttr("pageset", pageset)
						.putAttr("entity", taskLinkServiceImpl.getTasklinkEntity(ids))
						.returnModelAndView("project/TasklinkForm");
			}
			default:
				break;
			}
			return ViewMode.getInstance().returnModelAndView("project/TasklinkForm");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e + e.getMessage(), e).returnModelAndView("project/TasklinkForm");
		}
	}

	/**
	 * 修改條件表达式
	 *
	 * @return
	 */
	@RequestMapping("/expressform")
	public ModelAndView expressform(RequestMode pageset, String linkid) {
		try {
			// START-402880e5923170e10192317e069e0017
			String[] ids = linkid.split("-");
			List<Tasklink> node = taskLinkServiceImpl.getTasklinkBySTID(ids[0], ids[1]);
			if (node.size() <= 0) {
				throw new RuntimeException("未找到关系连线：" + linkid);
			}
			pageset.setOperateType(2);
			Tasklink link = node.get(0);
			return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("entity", link)
					.putAttr("stitle", link.getSnodeid()).putAttr("ttitle", link.getTnodeid())
					.returnModelAndView("project/TasklinkExpresstion");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e + e.getMessage(), e)
					.returnModelAndView("project/TasklinkExpresstion");
		}
	}

	public static String unescapeXml(String escapedText) {
		// Replace named entities
		escapedText = escapedText.replaceAll("&lt;", "<");
		escapedText = escapedText.replaceAll("&gt;", ">");
		escapedText = escapedText.replaceAll("&amp;", "&");
		escapedText = escapedText.replaceAll("&quot;", "\"");
		escapedText = escapedText.replaceAll("&apos;", "'");

		// Optionally handle numeric entities like & #39 ;
		Pattern pattern = Pattern.compile("&#(\\d+);");
		Matcher matcher = pattern.matcher(escapedText);
		while (matcher.find()) {
			int decimal = Integer.parseInt(matcher.group(1));
			char ch = (char) decimal;
			escapedText = escapedText.replace(matcher.group(), Character.toString(ch));
		}

		return escapedText;
	}

	/**
	 * 提交修改数据
	 * 
	 * @return
	 */
	@RequestMapping("/editExpresstion")
	@ResponseBody
	public Map<String, Object> editExpresstion(Tasklink entity, HttpSession session) {
		try {
			entity.setExpression(unescapeXml(entity.getExpression()));
			entity = taskLinkServiceImpl.editTasklinkExpresstion(entity, getCurrentUser(session));
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).putAttr("entity", entity).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).setError(e.getMessage(), e).returnObjMode();
		}
	}
}
